package middlewareorid.engine;

import waba.io.Catalog;
import waba.sys.Settings;
import waba.sys.Vm;

public class ConfigAccess {
	
	public int APP_NAME = 0;
	
	public int APP_DESCRIPTION = 1;
	
	public int APP_BLOGS = 2;
	
	public int APP_BLOGS_TYPE = 3;
	
	public int APP_USER = 4;
	
	public int APP_PASSWORD = 5;
	
	public int APP_STYLE = 6;
	
	public int APP_UI = 7;
	
	final int paramLength = 100;
	
	private Catalog c;

	public ConfigAccess() {
	}
	
	public void init() {
		/*
		 * Config using catalog
		 */
		c = new Catalog("djokdja_pref.Crtr.Type",Catalog.READ_ONLY);
		if (!c.isOpen())
		{
			c = new Catalog("djokdja_pref.Crtr.Type",Catalog.CREATE);
			Vm.debug("Catalog created ...");
			
			// App_Name = 0
			String data = initConfigValue("DJOKDJA");
			byte[] b = data.getBytes();	
			c.addRecord(b.length);
			c.writeBytes(b, 0, paramLength);
			// App_Description = 1
			data = initConfigValue("Mobile Blogs Tools - 2006@blogs.or.id");
			b = data.getBytes();
			c.addRecord(b.length);
			c.writeBytes(b, 0, paramLength);
			// App_Blogs = 2
			data = initConfigValue("http://blogs.or.id");
			b = data.getBytes();
			c.addRecord(b.length);
			c.writeBytes(b, 0, paramLength);
			// App_Blogs_Type = 3
			data = initConfigValue("0");
			b = data.getBytes();
			c.addRecord(b.length);
			c.writeBytes(b, 0, paramLength);
			// App_User = 4
			data = initConfigValue("sample");
			b = data.getBytes();
			c.addRecord(b.length);
			c.writeBytes(b, 0, paramLength);
			// App_Password = 5
			data = initConfigValue("sample");
			b = data.getBytes();
			c.addRecord(b.length);
			c.writeBytes(b, 0, paramLength);
			// App_Style = 6
			data = initConfigValue("1");
			b = data.getBytes();
			c.addRecord(b.length);
			c.writeBytes(b, 0, paramLength);
		}
		c.close();
		Vm.debug(Settings.dataPath);		
	}
	
	private String initConfigValue(String value) {
		String result = " ";
		for (int i=0; i<paramLength; i++) {
			result = result + " ";
		}
		result = (value.trim() + result).substring(0,paramLength);		
		return result;		
	}
	
	public String getConfigFromCatalog(int key) {
		String result = "";
		c = new Catalog("djokdja_pref.Crtr.Type",Catalog.READ_ONLY);
		if (c.isOpen())
		{
			c.setRecordPos(key);
			byte b[] = new byte[paramLength];
			c.readBytes(b, 0, paramLength);
			result = (new String(b)).trim();
			c.close();
		}
		return result;
	}

	public String setConfigToCatalog(int key, String data) {
		String result = "";
		c = new Catalog("djokdja_pref.Crtr.Type",Catalog.READ_WRITE);
		if (c.isOpen())
		{
			if (!c.setRecordPos(key)) c.addRecord(paramLength);
			String initData = " ";
			for (int i=0; i<paramLength; i++) {
				initData = initData + " ";
			}
			data = (data + initData).substring(0,paramLength);
			byte[] b = data.getBytes();	
			c.writeBytes(b, 0, paramLength);
			c.close();
		}
		return result;
	}
}
